﻿using Microsoft.AspNetCore.Mvc;
using Mvc.Sample.Data;
using Mvc.Sample.Models;
using X.PagedList.EF;

namespace Mvc.Sample.Areas.Todo.Controllers;

[Area("Todo")]
public class HomeController(
    ApplicationDbContext context) 
    : Controller
{
    [HttpGet]
    public async Task<IActionResult> Index(int ?page = 1, string? title = null)
    {
        var pageNumber = page ?? 1;
        var items = await context.TodoItems
            .Where(i => string.IsNullOrEmpty(title) || i.Title.Contains(title))
            .ToPagedListAsync(pageNumber, 2);
        return View(items);
    }
    
    public IActionResult Create()
    {
        return View();
    }
    
    [HttpPost]
    public async Task<IActionResult> Create(TodoItem todoItem)
    {
        if (ModelState.IsValid)
        {
            context.TodoItems.Add(todoItem);
            await context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(todoItem);
    }
    
    public async Task<IActionResult> Edit(int id)
    {
        var item = await context.TodoItems.FindAsync(id);
        if (item == null)
        {
            return NotFound();
        }
        return View(item);
    }
    
    [HttpPost]
    public async Task<IActionResult> Edit(TodoItem todoItem)
    {
        if (ModelState.IsValid)
        {
            context.Update(todoItem);
            await context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(todoItem);
    }
    
    public async Task<IActionResult> Delete(int id)
    {
        var item = await context.TodoItems.FindAsync(id);
        if (item != null)
        {
            context.TodoItems.Remove(item);
            await context.SaveChangesAsync();
        }
        return RedirectToAction(nameof(Index));
    }
    
    [HttpGet]
    public async Task<IActionResult> Details(int id)
    {
        var item = await context.TodoItems.FindAsync(id);
        return View(item);
    }
}
